﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections;

namespace ShumaDaf
{
    /// <summary>
    /// Interaction logic for DataTabControl.xaml
    /// </summary>
    public partial class DataTabControl : UserControl
    {
        private Setta mySettings;
        public DataTabControl()
        {
            InitializeComponent();
            
        }

        #region publicProperties
        
        private string _path;

        public double vis
        {
            set
            {
                this.dg1.Height = value;
                this.Height = value;
            }
        }

        public string PathToXmlFile
        {
            get { return _path; }
            set
            {
                _path = value;
                XmlDataProvider pr = (XmlDataProvider)Resources["myXmlDataTable"];
                
                pr.Source = new Uri(_path, UriKind.Absolute);
                pr.Refresh();
            }
        }

        /// <summary>
        /// flag, indicate forign table, don't modificate this!
        /// </summary>
        public Boolean ForiegnXml
        {
            get;
            set;
        }

        #endregion

        private void dg1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            if (ForiegnXml) return;
            XmlElement x = (XmlElement)e.Row.Item;
            XmlNode modified = x.SelectSingleNode("Modified");
            if (modified == null)
            {
                modified = x.AppendChild(x.OwnerDocument.CreateElement("Modified"));
            }
        }

        private void dataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = (DataGridCell)sender;

            string path = ((TextBlock)(cell.Content)).Text;
            if (Directory.Exists(path)) Process.Start("Explorer.exe", "\"" + path + "\"");
        }

        private void MediaInfo_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = (DataGridCell)sender;

            if (cell.IsEditing)
            {
                cell.IsEditing = false;
                e.Handled = true;
            }

        }
        #region SaveColumnsPosition
        private void restoreColumnsFromSettings()
        {
            DataSet ds = mySettings.getSettings();
            if (ds == null) return;
            /// выполняем проверку исключения, чтобы избежать кривого файла настроек
            try
            {
                {
                    // Sorting 
                    DataView dataView = new DataView(ds.Tables["TableProperties"]);
                    dataView.Sort = "index DESC";

                    foreach (DataRowView r in dataView)
                    {
                        int n = (int)(r["n"]);
                        DataGridColumn c = dg1.Columns[n];

                        c.Width = (double)r["width"];
                        c.Visibility = (bool)r["visible"] ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
                        c.DisplayIndex = (int)r["index"];
                    }
                }
            }
            catch (Exception)
            {
                mySettings.broken();
            }

        }
        private void savePosition()
        {
            if (ForiegnXml)
                return;

            try
            {
                mySettings.clearTableProp();
                for (int i = 0; i < dg1.Columns.Count; i++)
                {
                    DataGridColumn c = dg1.Columns[i];
                    mySettings.addTableProp(i, c.Width, c.Visibility, c.DisplayIndex, c.Header.ToString());
                }
                mySettings.writeSettings();
            }
            catch (Exception) { }
        }
        #endregion

        private void dg1_Loaded(object sender, RoutedEventArgs e)
        {
            mySettings = new Setta(FindVisualParent<MainWindow>(this));
            restoreColumnsFromSettings();
        }

        #region RowContexMenu
        private string RowMenuPath = null;
        private XmlElement RowMenuElement = null;

        // add context menu
        private void eventDataGridRowMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {

            if (ForiegnXml) return;

            string path = null;
            string name = null;
            XmlElement x = null;
            RowMenuPath = null;
            try
            {
                DataGridRow r = sender as DataGridRow;
                x = (XmlElement)r.Item;

                path = x.SelectSingleNode("Path").FirstChild.Value;
                name = x.SelectSingleNode("LocalTitle").FirstChild.Value;
            }
            catch (Exception) { return; }
            RowMenuPath = path;
            RowMenuElement = x;
            ContextMenu cxActions = new ContextMenu();

            MenuItem mi = new MenuItem();
            mi.Header = "Movie '" + name + "' is bullshit! Delete Folder forever!";
            mi.Click += new RoutedEventHandler(mi_Click);
            cxActions.Items.Add(mi);

            MenuItem mi2 = new MenuItem();
            mi2.Header = "Movie '" + name + "' mistake! Clear MyMovies metadata";
            mi2.Click += new RoutedEventHandler(mi2_Click);
            cxActions.Items.Add(mi2);

            MenuItem mi3 = new MenuItem();
            mi3.Header = "I delete this movie. it's not offline. It's Erased!";
            mi3.Click += new RoutedEventHandler(mi3_Click);
            cxActions.Items.Add(mi3);

            dg1.ContextMenu = cxActions;
            cxActions.IsOpen = true;
        }

        void mi3_Click(object sender, RoutedEventArgs e)
        {
            RowMenuElement.ParentNode.RemoveChild(RowMenuElement);
            XmlDataProvider pr = (XmlDataProvider)Resources["myXMLdata"];
            XmlDocument doc = pr.Document;
            MMovies.saveXML(doc, FindVisualParent<MainWindow>(this));
        }

        

        // erase directory
        void mi_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(RowMenuPath))
            {
                Directory.Delete(RowMenuPath, true);
            }
            mi3_Click(null, null);

        }

        //clear metadata
        void mi2_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(RowMenuPath))
            {
                FileInfo[] files = new DirectoryInfo(RowMenuPath).GetFiles("Mymovies.xml", SearchOption.AllDirectories);
                foreach (FileInfo fi in files)
                {
                    fi.Delete();
                }
            }
        }
        #endregion

        #region checkboxSingleClick
        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            XmlElement x = (XmlElement)row.Item;
                            XmlNode modified = x.SelectSingleNode("Modified");
                            if (modified == null)
                            {
                                modified = x.AppendChild(x.OwnerDocument.CreateElement("Modified"));
                            }
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }
        #endregion

        private void dg1_Sorting(object sender, DataGridSortingEventArgs e)
        {
            DataGridColumn column = e.Column;
            string path = "";
            string HandledPaths = "Size CollectionNumber RunningTime";
            if (column is DataGridTextColumn)
            {
                DataGridTextColumn tcol = (DataGridTextColumn)e.Column;
                Binding b = (Binding)tcol.Binding;
                path = b.XPath;
                if (HandledPaths.Contains(path))
                {
                    e.Handled = true;
                    IComparer comparer = null;
                    ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
                    //set the sort order on the column
                    column.SortDirection = direction;
                    column.GetLocalValueEnumerator();
                    ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg1.ItemsSource);

                    //comparer = new IntsInStringComparer(direction, path);
                    //lcv.CustomSort = comparer;

                }
                else
                    return;
            }
        }
    }
}
